<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */


namespace app\shop_admin\service;


use app\shop_admin\model\Configuration;
use app\Oss;
use app\shop_admin\model\Pic;
use app\shop_admin\model\PicCount;
use app\shop_admin\model\PicGroup;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\HttpException;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Filesystem;

class PicService
{
    public $merchantId;
    public $mallId;

    public function __construct()
    {
        global $user;
        $this->merchantId = $user->merchant_id;
        $this->mallId = $user->mall_id;
    }

    /**图片列表
     * @param array $data
     * @param int $page
     * @param int $size
     * @return array
     * @throws DbException
     */
    public function picList(array $data, int $page, int $size)
    {
        $pics = Pic::where($this->bulidWhere($data))
            ->alias('a')
            ->field('pic_name,pic_path,id,width,height')
            ->order('id desc')
            ->paginate(['page' => $page, 'list_rows' => $size]);
        foreach ($pics as $key => $value) {
            if (strstr($value['pic_path'], "https://") || strstr($value['pic_path'], "http://")) {
                $pics[$key]['pic_path'] = explode('/', $value['pic_path'], 4)[3];
            }
        }
        return [HTTP_SUCCESS, $pics];
    }

    /**添加图片
     * @param $files
     * @param $group_id
     * @return array
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function addPic($files, $group_id)
    {
        try {
            $file = 'test.txt';
            $fp = fopen($file, 'w');
            if (flock($fp, LOCK_EX)) {
                validate(['image' => 'fileExt:gif,jpg,png,jpeg'])->check($files);
                list($width, $height, $type, $attr) = getimagesize($files['image']);
                $size = bcdiv($files['image']->getsize(), 1024, 1);//getsize 获取到是字节
                $base_path = "storage/" . $this->mallId;
                if (!file_exists($base_path)) mkdir($base_path, 0777, true);
                $path = "storage/" . Filesystem::disk('public')->putFile($this->mallId, $files['image']);
                $con = Configuration::where('type', 'oss')->value('configuration');
                $js = json_decode($con, true);
                $up = "";

                if (!empty($js) && $js['oss_choice'] == 0) {

                    $oss = new Oss();
                    $object = $path;
                    $up = $oss->up($path, $object, $this->mallId);
                    if ($up) {
                        global $user;
                        $table = Db::name('lessee');
                        $table->where('id', $user->mall_id)
                            ->inc('oss_size', $size)
                            ->update();
                        if (file_exists($path)) @unlink($path);
                    }
                }
                $data = [
                    "merchant_id" => $this->merchantId,
                    "pic_group_id" => $group_id ?? null,
                    "pic_name" => $files['image']->getOriginalName(),
                    "pic_path" => empty($up) ? request()->server("REQUEST_SCHEME") . '://' . $_SERVER['HTTP_HOST'] . "/" . $path : $up,
                    "pic_size" => $size,
                    "width" => $width,
                    "height" => $height
                ];
                $up = Pic::create($data);
                if (!empty($group_id)) {
                    PicGroup::where('id', $group_id)->inc('count')->update();
                }
                flock($fp, LOCK_UN);
            }
            fclose($fp);
            return [HTTP_SUCCESS, $up ?? $path];
        } catch (\think\exception\ValidateException $e) {
            return [HTTP_UNPROCES, $e->getMessage()];
        }
    }

    /**添加图片
     * @param $files
     * @param $group_id
     * @return array
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function addLocalPic($path)
    {

        try {
            if (!file_exists($path)) {
                return [HTTP_UNPROCES, "图片不存在"];
            }
            $picGroup = PicGroup::where(['name' => '商品采集', 'mall_id' => $this->mallId, 'merchant_id' => $this->merchantId])->find();
            if (empty($picGroup)) {
                $picGroup = new PicGroup();
                $picGroup->name = "商品采集";
                $picGroup->count = 0;
                $picGroup->merchant_id = $this->merchantId;
                $picGroup->save();
            }
            $group_id = $picGroup->id ?? 0;

            $size = filesize($path);
            $originalName = pathinfo($path)['basename'];
            $file = 'test.txt';
            $fp = fopen($file, 'w');

            if (flock($fp, LOCK_EX)) {

                $con = Configuration::where('type', 'oss')->value('configuration');
                $js = json_decode($con, true);
                $up = "";

                if (!empty($js) && $js['oss_choice'] == 0) {

                    $oss = new Oss();
                    $object = $path;
                    $up = $oss->up($path, $object, $this->mallId);
                    if ($up) {
                        global $user;
                        $table = Db::name('lessee');
                        $table->where('id', $user->mall_id)
                            ->inc('oss_size', $size)
                            ->update();
                        if (file_exists($path)) @unlink($path);
                    }

                }
                $data = [
                    "merchant_id" => $this->merchantId,
                    "pic_group_id" => $group_id ?? null,
                    "pic_name" => $originalName,
                    "pic_path" => empty($up) ? request()->server("REQUEST_SCHEME") . '://' . $_SERVER['HTTP_HOST'] . "/" . $path : $up,
                    "pic_size" => $size,
                    "width" => 800,#$width,
                    "height" => 800,#$height
                ];
                Pic::create($data);

                if (!empty($group_id)) {
                    PicGroup::where('id', $group_id)->inc('count')->update();
                }

                flock($fp, LOCK_UN);
            }
            fclose($fp);

            return [HTTP_SUCCESS, $up ?? $path];
        } catch (\think\exception\ValidateException $e) {
            return [HTTP_UNPROCES, $e->getMessage()];
        }
    }

    /**
     *分组列表
     */
    public function groupList()
    {
        $arr = PicGroup::where('merchant_id', $this->merchantId)
            ->field('name,count,id')
            ->select()
            ->toArray();
        $pics = Pic::where('merchant_id', $this->merchantId)
            ->field("sum(case when isnull(pic_group_id)=1 then 1 else 0 end) as wfz,count(id) as total")
            ->find();
        array_unshift($arr, ['name' => "未分组", "count" => $pics['wfz']]);
        array_unshift($arr, ['name' => "全部", "count" => $pics['total']]);

        return [HTTP_SUCCESS, $arr];
    }

    /**
     *添加分组
     * @param array $data
     * @return array
     */
    public function addGroup(array $data)
    {
        $data['merchant_id'] = $this->merchantId;
        $create = PicGroup::create($data);
        return [HTTP_SUCCESS, $create];
    }

    /** 删除分组
     * @param int $id
     * @return void
     */
    public function delGroup(int $id)
    {
        PicGroup::destroy($id);
        Pic::where('merchant_id', $this->merchantId)
            ->where('pic_group_id', $id)
            ->update(['pic_group_id' => null]);
        return HTTP_NOCONTEND;
    }

    /**编辑分组
     * @param array $data
     * @return array
     */
    public function editGroup(array $data)
    {
        $id = $data['id'];
        unset($data['id']);
        $up = PicGroup::update($data, ['id' => $id]);
        return [HTTP_SUCCESS, $up];
    }

    /**
     * @param int $id
     * @return int
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function delPic(int $id)
    {
        $pic = Pic::find($id);
        $del = Pic::destroy($id);
        $res = @unlink($pic['pic_path']);
        if ($del && $res) {
            //PicCount::where('merchant_id', $this->merchantId)->inc('count', $pic['pic_size'])->update();
            PicGroup::where('id', $pic['pic_group_id'])->inc('count')->update();
        }

        return HTTP_NOCONTEND;
    }

    /**OSS配置
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function ossConfig(): array
    {
        global $user;
        $config = Configuration::where('mall_id', $user->mall_id)->where('type', 'oss')->find();
        if ($config['configuration']['oss_choice'] == 1) {
            $config1 = Db::table('jiecheng_saas_configuration')->where('type', 'oss')->find();
            $configuration = $config1['configuration'];
            unset($config1['configuration']);
            $config1['configuration'] = json_decode($configuration, true);
        }
        return [HTTP_SUCCESS, $config['configuration']['oss_choice'] == 1 ? $config1 : $config];
    }

    private function bulidWhere(array $data)
    {
        $where = [];
        $arr = [];
        $where[] = ['a.merchant_id', '=', $this->merchantId];
        !empty($data['pic_group_id']) && $where[] = ['a.pic_group_id', '=', $data['pic_group_id']];
        !empty($data['type']) && $where[] = ['a.pic_group_id', 'NULL', ''];
        !empty($data['pic_name']) && $where[] = ['a.pic_name', 'like', "%" . $data['pic_name'] . "%"];
        if (array_key_exists('start_time', $data) && array_key_exists('end_time', $data))
            $arr = $this->setTime($data['start_time'], $data['end_time']);
        return array_merge($where, $arr);
    }

    private function setTime($start_time, $end_time)
    {
        $arr = [];
        if (!empty($start_time) && !empty($end_time))
            $arr[] = ['a.create_time', 'between', [$start_time, $end_time]];
        elseif (!empty($start_time) && empty($end_time))
            $arr[] = ['a.create_time', 'between', [$start_time, date('Y-m-d H:i:s', time())]];
        elseif (empty($start_time) && !empty($end_time))
            $arr[] = ['a.create_time', 'between', [date('Y-m-d H:i:s', strtotime($end_time) - 60), $end_time]];
        return $arr;
    }

    /**
     * @param string $path
     * @param float $size
     * @throws DbException
     * @throws Exception
     */
    private function upOssSize(string $path, float $size)
    {
        global $user;
        $oss = new Oss();
        $object = $path;
        $table = Db::table('jiecheng_lessee');
        $table->where('id', $user->mall_id);
        $find = $table->find();
        $up = $oss->up($path, $object, $this->mallId);
        if ($up && $find['oss_size'] >= $size) {
            $table->inc('oss_size', $size)
                ->update();
            //if (file_exists($path)) @unlink($path);
        } else {
            throw new Exception('上传OSS失败！', HTTP_INVALID);
        }
    }


    public function getUrl()
    {
        $url = request()->server("REQUEST_SCHEME") . '://' . $_SERVER['HTTP_HOST'];
        $con = json_decode(Configuration::where('type', 'oss')->value('configuration'), true);

        if (!empty($con)) {
            if ($con['oss_choice'] == 1) {
                $url = request()->server("REQUEST_SCHEME") . '://' . $_SERVER['HTTP_HOST'];

            } else {
                if (isset($con['ali'])) {

                    switch ($con['is_open']) {
                        case 0:
                            $url = request()->server("REQUEST_SCHEME") . '://' . $_SERVER['HTTP_HOST'];
                            break;
                        case 1:
                            $is_customize = oss_is_customize($con['ali']['endpoint']);
                            $url = $is_customize ? $con['ali']['endpoint'] : "https://" . $con['ali']['bucket'] . "." . str_replace("https://", "", $con['ali']['endpoint']);
                            break;
                        case 2:
                            $url = $con['qcloud']['endpoint'];
                            break;
                    }
                }
            }

        } else {
            $url = request()->server("REQUEST_SCHEME") . '://' . $_SERVER['HTTP_HOST'];
        }
        return [HTTP_SUCCESS, $url];
    }
}